import { ElLoading } from 'element-plus'
import { gmindJsonToXmindJson } from './parse'
import { generateRandomId, setJsonUniqueId } from '../utils'
import xmindTheme from '../config/xmindTheme'
import { apiExportMindMapImage, apiExportMindMapPDF } from '@/apis/mind'

const JSZip = require('jszip')
const zip = new JSZip()

/**
 * 生成指定画布的html字符串
 * @param {*} svg
 * @param {*} fillColor
 * @returns
 */
async function getMindMapHtmlstr (svg, fillColor) {
  const spacing = 20
  const cloneSvg = svg.clone(true)
  cloneSvg.insert('g', '.map-outter-container').html(
    `<defs>
      <style>
        @font-face { font-family: 'audiowide'; font-style: normal; font-weight: regular; src: url('https://image.zdxblog.cn/fonts/Audiowide-Regular.ttf?v=0.3.7') format('truetype'); }
        @font-face { font-family: 'allseto'; font-style: normal; font-weight: regular; src: url('https://image.zdxblog.cn/fonts/cjkFonts-allseto.ttf?v=0.3.7') format('truetype'); }
        @font-face { font-family: 'nevermind'; font-style: normal; font-weight: regular; src: url('https://image.zdxblog.cn/fonts/NeverMind-Regular.ttf?v=0.3.7') format('truetype'); }
        @font-face { font-family: 'nevermindhand'; font-style: normal; font-weight: regular; src: url('https://image.zdxblog.cn/fonts/NeverMindHand-Regular.ttf?v=0.3.7') format('truetype'); }
        @font-face { font-family: 'Arvo'; font-style: normal; font-weight: regular; src: url('https://image.zdxblog.cn/fonts/Arvo.ttf?v=0.3.7') format('truetype'); }
      </style>
    </defs>`
  )
  const container = cloneSvg.select('.map-outter-container').attr('transform', 'scale(1)')
  const { width: cwidth, height: cheight, top: ctop, left: cleft } = container.node().getBoundingClientRect()
  cloneSvg.insert('rect', '.map-outter-container').attr('x', 0).attr('y', 0).attr('width', cwidth + spacing * 2).attr('height', cheight + spacing * 2).attr('fill', fillColor)
  const { left, top } = container.select('.x-mind-root-theme').node().getBoundingClientRect()
  const transformX = left - cleft + spacing
  const transformY = top - ctop + spacing
  container.attr('transform', `translate(${transformX}, ${transformY})`)
  cloneSvg
    .attr('width', cwidth + spacing * 2)
    .attr('height', cheight + spacing * 2)
    .selectAll('.node-text-description, .node-summary-description').style('white-space', 'pre-wrap').style('line-height', 'inherit').style('padding', 0).style('margin', 0)
  cloneSvg.remove()
  return cloneSvg.node().outerHTML
}

/**
 * 思维导图导出为svg
 * @param {*} svg
 * @param {*} fillColor
 */
export async function exportMindMapSvg (svg, fillColor, mapName) {
  const htmlStr = await getMindMapHtmlstr(svg, fillColor)
  const blob = new Blob([htmlStr], {
    type: 'image/svg+xml'
  })
  const file = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = file
  a.download = `${mapName}.svg`
  a.click()
}

/**
 * 画布导出为png和jpeg
 * @param {*} mindId
 * @param {*} mapId
 * @param {*} type
 */
export async function exportMinMapImage (mindId, mapId, type) {
  const loadingInstance = ElLoading.service({ text: 'MindMap 正在导出图片. . .' })
  try {
    const data = await apiExportMindMapImage({ mindId, mapId, type })
    const url = window.URL.createObjectURL(data.data)
    const a = document.createElement('a')
    a.href = url
    const imageFillName = data.headers['content-disposition'].split('=')[1]
    const name = imageFillName.split('.')[0]
    a.download = `${decodeURIComponent(name)}.${type}`
    a.click()
    window.URL.revokeObjectURL(url)
  } finally {
    loadingInstance.close()
  }
}

/**
 * 画布导出为pdf
 * @param {*} mindId
 * @param {*} mapId
 */
export async function exportMinMapPDF (mindId, mapId) {
  const loadingInstance = ElLoading.service({ text: 'MindMap 正在导出PDF. . .' })
  try {
    const data = await apiExportMindMapPDF({ mindId, mapId })
    const url = window.URL.createObjectURL(data.data)
    const a = document.createElement('a')
    a.href = url
    const imageFillName = data.headers['content-disposition'].split('=')[1]
    const name = imageFillName.split('.')[0]
    a.download = `${decodeURIComponent(name)}.pdf`
    a.click()
    window.URL.revokeObjectURL(url)
  } finally {
    loadingInstance.close()
  }
}

/**
 * 思维导图导出JSON
 * @param {*} name
 * @param {*} json
 */
export function exportMindMapJson (name, data) {
  const copydata = JSON.parse(JSON.stringify(data))
  copydata.id = generateRandomId()
  setJsonUniqueId(copydata.rootTopic, true)
  const blob = new Blob([JSON.stringify(copydata)])
  const file = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = file
  a.download = `${name}.json`
  a.click()
}

/**
 * 导出自定义专属gmind文件
 * @param {*} name
 * @param {*} data
 */
export async function exportMindMapToGmind (name, data) {
  const copydata = JSON.parse(JSON.stringify(data))
  copydata.id = generateRandomId()
  setJsonUniqueId(copydata.rootTopic, true)
  zip.file('content.json', JSON.stringify(copydata))
  const content = await zip.generateAsync({ type: 'blob' })
  const file = URL.createObjectURL(content)
  const a = document.createElement('a')
  a.href = file
  a.download = `${name}.gmind`
  a.click()
}

function getXmindContentXmlData () {
  return ` < ?xml version = "1.0"encoding = "UTF-8"standalone = "no" ? ><xmap - content xmlns = "urn:xmind:xmap:xmlns:content:2.0"xmlns: fo = "http://www.w3.org/1999/XSL/Format"xmlns: svg = "http://www.w3.org/2000/svg"xmlns: xhtml = "http://www.w3.org/1999/xhtml"xmlns: xlink = "http://www.w3.org/1999/xlink"modified - by = "bruce"timestamp = "1503058545540"version = "2.0" > <sheet id = "7abtd0ssc7n4pi1nu6i7b6lsdh"modified - by = "bruce"theme = "0kdeemiijde6nuk97e4t0vpp54"timestamp = "1503058545540" > <topic id = "1vr0lcte2og4t2sopiogvdmifc"modified - by = "bruce"structure - class = "org.xmind.ui.logic.right"timestamp = "1503058545417" > <title > Warning警告Attention Warnung경고 < /title>            <children>                <topics type="attached">                    <topic id="71h1aip2t1o8vvm0a41nausaar" modified-by="bruce" timestamp="1503058545423">                        <title svg:width="500">This file can not be opened normally, please do not modify and save, otherwise the contents will be permanently lost！</title > <children > <topics type = "attached" > <topic id = "428akmkh9a0tog6c91qj995qdl"modified - by = "bruce"timestamp = "1503058545427" > <title > You can
  try using XMind 8 Update 3 or later version to open < /title>                                </topic > </topics>                        </children > </topic>                    <topic id="2kb87f8m38b3hnfhp450c7q35e" modified-by="bruce" timestamp="1503058545434">                        <title svg:width="500">该文件无法正常打开，请勿修改并保存，否则文件内容将会永久性丢失！</title > <children > <topics type = "attached" > <topic id = "3m9hoo4a09n53ofl6fohdun99f"modified - by = "bruce"timestamp = "1503058545438" > <title > 你可以尝试使用XMind 8 Update 3或更新版本打开 < /title>                                </topic > </topics>                        </children > </topic>                    <topic id="7r3r4617hvh931ot9obi595r8f" modified-by="bruce" timestamp="1503058545444">                        <title svg:width="500">該文件無法正常打開，請勿修改並保存，否則文件內容將會永久性丟失！</title > <children > <topics type = "attached" > <topic id = "691pgka6gmgpgkacaa0h3f1hjb"modified - by = "bruce"timestamp = "1503058545448" > <title > 你可以嘗試使用XMind 8 Update 3或更新版本打開 < /title>                                </topic > </topics>                        </children > </topic>                    <topic id="0f2e3rpkfahg4spg4nda946r0b" modified-by="bruce" timestamp="1503058545453">                        <title svg:width="500">この文書は正常に開かないので、修正して保存しないようにしてください。そうでないと、書類の内容が永久に失われます。！</title > <children > <topics type = "attached" > <topic id = "4vuubta53ksc1falk46mevge0t"modified - by = "bruce"timestamp = "1503058545457" > <title > XMind 8 Update 3や更新版を使って開くこともできます < /title>                                </topic > </topics>                        </children > </topic>                    <topic id="70n9i4u3lb89sq9l1m1bs255j5" modified-by="bruce" timestamp="1503058545463">                        <title svg:width="500">Datei kann nicht richtig geöffnet werden. Bitte ändern Sie diese Datei nicht und speichern Sie sie, sonst wird die Datei endgültig gelöscht werden.</title > <children > <topics type = "attached" > <topic id = "1qpc5ee298p2sqeqbinpca46b7"modified - by = "bruce"timestamp = "1503058545466" > <title svg: width = "500" > Bitte versuchen Sie,
  diese Datei mit XMind 8 Update 3 oder später zuöffnen. < /title>                                </topic > </topics>                        </children > </topic>                    <topic id="4dmes10uc19pq7enu8sc4bmvif" modified-by="bruce" timestamp="1503058545473">                        <title svg:width="500">Ce fichier ne peut pas ouvert normalement, veuillez le rédiger et sauvegarder, sinon le fichier sera perdu en permanence. </title > <children > <topics type = "attached" > <topic id = "5f0rivgubii2launodiln7sdkt"modified - by = "bruce"timestamp = "1503058545476" > <title svg: width = "500" > Vous pouvez essayer d 'ouvrir avec XMind 8 Update 3 ou avec une version plus récente.</title>                                </topic>                            </topics>                        </children>                    </topic>                    <topic id="10pn1os1sgfsnqa8akabom5pej" modified-by="bruce" timestamp="1503058545481">                        <title svg:width="500">파일을 정상적으로 열 수 없으며, 수정 및 저장하지 마십시오. 그렇지 않으면 파일의 내용이 영구적으로 손실됩니다!</title>                        <children>                            <topics type="attached">                                <topic id="0l2nr0fq3em22rctapkj46ue58" modified-by="bruce" timestamp="1503058545484">                                    <title svg:width="500">XMind 8 Update 3 또는 이후 버전을 사용하여</title>                                </topic>                            </topics>                        </children>                    </topic>                </topics>            </children>            <extensions>                <extension provider="org.xmind.ui.map.unbalanced">                    <content>                        <right-number>-1</right-number>                    </content>                </extension>            </extensions>        </topic>        <title>Sheet 1</title>    </sheet></xmap-content>`
}

function generateXmindRootJson () {
  return {
    id: `gimiMindMap_${Date.now()}`,
    class: 'sheet',
    title: '思维导图',
    extensions: [],
    topicPositioning: 'fixed',
    topicOverlapping: 'overlap',
    coreVersion: '2.100.0'
  }
}

/**
 * 思维导图导出.xmind文件
 * @param {*} displaySheet
 */
export async function exportMindMapToXmind (displaySheet, structureClass) {
  const xmindObject = generateXmindRootJson(structureClass)
  const { rootTopic, relationships } = gmindJsonToXmindJson(displaySheet.rootTopic, structureClass)
  const xmindJsonString = JSON.stringify([
    {
      ...xmindObject,
      rootTopic,
      relationships,
      theme: xmindTheme
    }
  ])
  zip.file('content.json', xmindJsonString)

  zip.file(
    'metadata.json',
  `{"modifier":"","dataStructureVersion":"2","creator":{"name":"mind-map"},"layoutEngineVersion":"3","activeSheetId":"${xmindObject.id}"}`
  )

  zip.file('content.xml', getXmindContentXmlData())

  const manifestData = {
    'file-entries': {
      'content.json': {},
      'metadata.json': {},
      'Thumbnails/thumbnail.png': {}
    }
  }
  zip.file('manifest.json', JSON.stringify(manifestData))

  const content = await zip.generateAsync({ type: 'blob' })

  const file = URL.createObjectURL(content)
  const a = document.createElement('a')
  a.href = file
  a.download = `${displaySheet.name}.xmind`
  a.click()
}
